package com.webserver.core;

import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

/**
 * @author Administrator
 * @Description
 * @date 2022/5/17 11:45
 **/
public class DispatchServlet {
    private static File rootDir;
    public static File staticDir;

    static {
        try {
            rootDir = new File(
                    DispatchServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(rootDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    public void service(HttpServletRequest request, HttpServletResponse response) {
        //处理请求
        String uri = request.getRequestURI();
       if ("/myweb/reg".equals(uri)){
           System.out.println("开始处理用户注册!!!!!!!!!!!!!");
           new UserController().reg(request, response);

       }else if("/myweb/login".equals(uri)){
           System.out.println("开始处理用户登录!!!!!!!!!!!!");
           new UserController().login(request, response);
       }
       else {
           File file = new File(staticDir, uri);

           if (file.isFile()) {
               response.setContentFile(file);
           } else {
               response.setStatesCode(404);
               response.setStatesReason("NotFound");
               file = new File(staticDir, "/root/404.html");
               response.setContentFile(file);

           }
       }
        response.addHeader("Server", "WebServer");
    }
}
